<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
    >
      <el-form-item label="选择雇主" prop="employerId">
        <el-input
          v-model="queryParams.employerId"
          placeholder="请输入所属雇主"
          :show-word-limit="true"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="部门" prop="createBy">
        <el-input
          v-model="queryParams.createBy"
          placeholder="请输入发布人"
          :show-word-limit="true"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="雇员姓名" prop="employerId">
        <el-input
          v-model="queryParams.employerId"
          placeholder="请输入雇员姓名"
          :show-word-limit="true"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <div class="option-block" v-if="editStatus">
      <div class="option-line">
        <div class="line-label">班次：</div>
        <div class="line-value">
          <el-checkbox-group v-model="checkboxGroup1" :max="3">
            <el-checkbox
              :label="item.id"
              v-for="(item, index) in classesList"
              :key="index"
              >{{ item.classesName }}</el-checkbox
            >
          </el-checkbox-group>
        </div>
      </div>
      <div class="option-line">
        <div class="line-label">周期班：</div>
        <div class="line-value">
          <el-checkbox-group v-model="checkboxGroup2" :max="3">
            <el-checkbox
              :label="item.id"
              v-for="(item, index) in cycleList"
              :key="index"
              >{{ item.classeName }}</el-checkbox
            >
          </el-checkbox-group>
        </div>
      </div>
      <div class="option-line" style="align-items: center">
        <div class="line-label">状态：</div>
        <div class="line-value">
          <el-radio-group v-model="postStatus">
            <el-radio-button label="0">全部</el-radio-button>
            <el-radio-button label="1">已发布</el-radio-button>
            <el-radio-button label="2">未发布</el-radio-button>
          </el-radio-group>
        </div>
      </div>
    </div>

    <el-row
      :gutter="20"
      type="flex"
      align="middle"
      justify="space-between"
      class="mb8"
    >
      <el-col :span="1.5">
        <el-select v-model="currentYear" @change="selectYear">
          <el-option
            :label="item.label"
            :value="item.value"
            v-for="(item, index) in yearArr"
            :key="index"
          >
          </el-option>
        </el-select>
      </el-col>
      <el-col :span="1" v-for="(item, index) in 12" :key="index">
        <div
          class="month-text"
          :class="{ active: currentMonth == index }"
          @click="selectMonth(index + 1)"
        >
          {{ index + 1 }}月
        </div>
      </el-col>
      <el-col :span="1.5">
        <el-button-group>
          <el-button icon="el-icon-arrow-left" @click="lastWeek"
            >上一周</el-button
          >
          <el-button @click="nextWeek"
            >下一周<i class="el-icon-arrow-right el-icon--right"></i
          ></el-button>
        </el-button-group>
      </el-col>
    </el-row>

    <el-table
      :data="dataList"
      border
      style="width: 100%; color: black"
      ref="mainTable"
      @selection-change="handleSelectionChange"
      @header-click="handleHeaderClick"
      @cell-dblclick="handleCellDblclick"
      @row-click="handleRowClick"
      :max-height="tableHeight"
    >
      <el-table-column
        type="selection"
        width="55"
        align="center"
        v-if="editStatus"
      />
      <el-table-column
        property="name"
        fixed
        label="组员姓名"
        align="center"
        width="120"
      />
      <el-table-column
        align="center"
        v-for="(item, index) in dateArr"
        :key="index + item"
        :label="formatDate(new Date(item), 'm/d', true)"
        :render-header="todayDate == item ? renderHeader : renderNot"
        :column-key="index+''"
      >
        <template slot-scope="scope">
          <span>1212121</span>
        </template>
      </el-table-column>
    </el-table>

    <el-row
      :gutter="20"
      type="flex"
      align="middle"
      justify="end"
      style="margin-top: 20px"
    >
      <el-button type="primary" plain @click="batchOption">批量排班</el-button>

      <template v-if="editStatus">
        <el-button type="info" plain @click="editOption(false)"
          >取消编辑</el-button
        >
        <el-button type="warning" plain @click="saveOption">保存</el-button>
      </template>
      <el-button type="success" plain @click="editOption(true)" v-else
        >编辑排班</el-button
      >
      <el-button type="primary" @click="postOption">发布</el-button>
    </el-row>

    <!-- 添加或修改周期班对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="排班形式" prop="type">
          <el-select v-model="form.type" placeholder="请选择排班形式">
            <el-option label="班次排班" value="1"> </el-option>
            <el-option label="周期排班" value="2"> </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="排班方式" prop="type1">
          <el-select v-model="form.type1" placeholder="请选择排班方式">
            <el-option label="循环周期排班" value="1"> </el-option>
            <el-option label="月历排班" value="2"> </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="选择班次" prop="classesList" v-if="form.type == 1">
          <el-checkbox-group v-model="form.classesList">
            <el-checkbox
              :label="item.classesName"
              v-for="(item, index) in classesList"
              :key="index"
            ></el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="选择周期班" prop="cycleList" v-if="form.type == 2">
          <el-checkbox-group v-model="form.cycleList">
            <el-checkbox
              :label="item.classeName"
              v-for="(item, index) in cycleList"
              :key="index"
            ></el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="循环周期" prop="loopCycle">
          <el-date-picker
            v-model="form.loopCycle"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="yyyy-MM-dd"
            :picker-options="pickerOptions"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="按周排班" prop="week" v-if="form.type == 1">
          <el-checkbox-group v-model="form.week">
            <el-checkbox
              :label="item"
              v-for="(item, index) in weekList"
              :key="index"
              >{{ item }}</el-checkbox
            >
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="选择组员">
          <el-button @click="checkTeamMember">选择组员</el-button>
          <div style="margin-top: 10px">
            <el-tag
              :key="index"
              v-for="(item, index) in checkTeamMemberList"
              closable
              :disable-transitions="false"
              @close="handleRemoveTeamMember(index)"
              style="margin-right: 10px"
            >
              {{ item.name }}
            </el-tag>
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog
      title="选择组员"
      :visible.sync="teamOpen"
      width="800px"
      append-to-body
    >
      <el-table
        ref="multipleTable"
        v-loading="loading"
        :data="teamMemberList"
        @selection-change="handleTeamMemberChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column
          label="组员名称"
          align="center"
          prop="name"
          :show-overflow-tooltip="true"
        />
      </el-table>
    </el-dialog>
  </div>
</template>

<script>
import { listCycle } from "@/api/checkWork/cycle";
import { listClasses } from "@/api/checkWork/classes";
export default {
  name: "calendar",
  components: {},
  data() {
    let _minTime = null;
    let _maxTime = null;
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 周期班表格数据
      cycleList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {},
      userList: [],

      dataList: [
        {
          name: "张三",
        },
        {
          name: "李四",
        },
        {
          name: "王五",
        },
      ],
      dateArr: [],
      currentFirstDate: null,
      currentMonth: null,
      currentYear: null,
      todayYear: null,
      todayDate: null,
      editStatus: false,
      weekList: ["周日", "周一", "周二", "周三", "周四", "周五", "周六"],

      cycleList: [],
      classesList: [],
      pickerOptions: {
        onPick(time) {
          // 如果选择了只选择了一个时间
          if (!time.maxDate) {
            let timeRange = 3600 * 1000 * 24 * 365 * 3; // 3年
            _minTime = time.minDate.getTime() - timeRange; // 最小时间
            _maxTime = time.minDate.getTime() + timeRange; // 最大时间
            // 如果选了两个时间，那就清空本次范围判断数据，以备重选
          } else {
            _minTime = _maxTime = null;
          }
        },
      },
      teamOpen: false,
      teamMemberList: [],
      checkTeamMemberList: [],

      checkboxGroup1: [],
      checkboxGroup2: [],
      postStatus: "0",
    };
  },
  created() {
    // this.getList();
    this.getData();
    this.setDate(new Date());
    this.todayYear = new Date().getFullYear();
    this.todayDate = this.formatDate(new Date(), "Y/m/d");
    let yearList = [];
    for (var i = this.todayYear - 2; i <= this.todayYear + 2; i++) {
      yearList.push({
        value: i,
        label: i,
      });
    }
    this.yearArr = yearList;
  },
  computed: {},
  watch: {
    teamMemberList: {
      handler(newValue) {
        if (this.checkTeamMemberList.length && newValue.length) {
          let list = [];
          this.teamMemberList.forEach((item) => {
            this.checkTeamMemberList.forEach((val) => {
              if (val.id === item.id) {
                list.push(item);
              }
            });
          });
          if (list.length) {
            this.$nextTick(() => {
              list.forEach((row) => {
                this.$refs.multipleTable.toggleRowSelection(row, true);
              });
            });
          }
        }
      },
      immediate: true,
    },
  },
  methods: {
    addDate(date, num) {
      date.setDate(date.getDate() + num);
      return date;
    },
    setDate(date) {
      const week = date.getDay() - 1;
      date = this.addDate(date, week * -1);
      this.currentFirstDate = new Date(date);
      this.currentMonth = this.currentFirstDate.getMonth();
      this.currentYear = this.currentFirstDate.getFullYear();
      let dateList = [];
      for (var i = 0; i < 7; i++) {
        dateList.push(
          this.formatDate(i == 0 ? date : this.addDate(date, 1), "Y/m/d")
        );
      }
      this.dateArr = dateList;
    },
    //格式化时间
    formatDate(dateValue, format, isWeek) {
      if (typeof format === "undefined" || format === null) {
        format = "Y-m-d h:i:s";
      }
      if (dateValue == null || dateValue == "") return "";
      var d = new Date(dateValue);

      const date = {
        Y: d.getFullYear(),
        "m+": d.getMonth() + 1 < 10 ? `0${d.getMonth() + 1}` : d.getMonth() + 1,
        "d+": d.getDate() < 10 ? `0${d.getDate()}` : d.getDate(),
        "h+": d.getHours() < 10 ? `0${d.getHours()}` : d.getHours(),
        "i+": d.getMinutes() < 10 ? `0${d.getMinutes()}` : d.getMinutes(),
        "s+": d.getSeconds() < 10 ? `0${d.getSeconds()}` : d.getSeconds(),
        "q+": Math.floor((d.getMonth() + 3) / 3),
        "S+": d.getMilliseconds(),
      };

      for (let k in date) {
        if (new RegExp("(" + k + ")").test(format)) {
          format = format.replace(
            RegExp.$1,
            RegExp.$1.length === 1
              ? date[k]
              : ("00" + date[k]).substr(("" + date[k]).length)
          );
        }
      }
      if (isWeek) {
        const week = this.weekList[d.getDay()];
        format = format + week;
      }
      return format;
    },
    //上一周
    lastWeek() {
      this.setDate(this.addDate(this.currentFirstDate, -7));
    },
    //下一周
    nextWeek() {
      this.setDate(this.addDate(this.currentFirstDate, 7));
    },
    //切换月份
    selectMonth(month) {
      const date = `${this.currentYear}/${month > 9 ? month : `0${month}`}/01`;
      const weekOne = this.getFirstDayOfWeek(new Date(date));
      //如果当前月第一天不是周一则往后切一周
      if (new Date(weekOne).getMonth() + 1 == month) {
        this.setDate(new Date(date));
      } else {
        this.setDate(this.addDate(new Date(date), 7));
      }
    },
    //获取当前日期所在周的周一的日期
    getFirstDayOfWeek(date) {
      var weekday = date.getDay() || 7;
      date.setDate(date.getDate() - weekday + 1);
      return this.formatDate(date, "Y/m/d");
    },
    //切换年份
    selectYear() {
      const date = `${this.currentYear}-${this.formatDate(new Date(), "m/d")}`;
      this.setDate(new Date(date));
    },
    renderNot(h, { column }) {
      return h("div", [h("span", column.label)]);
    },
    renderHeader(h, { column }) {
      return h("div", [
        h("span", column.label),
        h(
          "el-tooltip",
          {
            props: {
              effect: "dark",
              content: "今天",
              placement: "top-start",
            },
          },
          [
            h("i", {
              class: "el-icon-star-off",
              style:
                "color:#1890ff;margin-left:10px;cursor:pointer;font-size:14px;",
            }),
          ]
        ),
      ]);
    },
    //批量操作
    batchOption() {
      this.reset();
      this.open = true;
      this.title = "批量排班";
    },
    //编辑操作
    editOption(value) {
      this.editStatus = value;
    },
    //发布操作
    postOption() {},
    //保存操作
    saveOption() {},

    // 表单重置
    reset() {
      this.form = {
        id: null,
        type: null,
        type1: null,
        week: [],
        cycleList: [],
        classesList: [],
        loopCycle: [],
      };
      this.lookView = false;
      this.resetForm("form");
    },
    //请求页面所需数据
    getData() {
      listCycle({ pageSize: 100 }).then((response) => {
        this.cycleList = response.rows;
      });
      listClasses({ pageSize: 100 }).then((response) => {
        this.classesList = response.rows;
      });
    },
    //点击选择组员按钮
    checkTeamMember() {
      this.teamMemberList = [...this.dataList];
      this.teamOpen = true;
      this.loading = false;
    },
    handleTeamMemberChange(selection) {
      this.checkTeamMemberList = selection;
    },
    handleRemoveTeamMember(index) {
      this.checkTeamMemberList.splice(index, 1);
    },
    getStartAndEndDateOfWeek(date) {
      const millisecondsOfDay = 24 * 60 * 60 * 1000;
      let dayOfWeek = date.getDay();
      if (dayOfWeek === 0) dayOfWeek = 7;
      const startDate = new Date(
        date.getTime() - (dayOfWeek - 1) * millisecondsOfDay
      );
      const endDate = new Date(
        date.getTime() + (7 - dayOfWeek) * millisecondsOfDay
      );

      return { startDate, endDate };
    },

    /** 查询周期班列表 */
    getList() {
      this.loading = true;
      listCycle(this.queryParams).then((response) => {
        this.cycleList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      if (selection.length > 1) {
        let del_row = selection.shift();
        this.$refs.mainTable.toggleRowSelection(del_row, false); //设置这一行取消选中
      }
      console.log(selection);
      // this.ids = selection.map((item) => item.id);
      // this.single = selection.length !== 1;
      // this.multiple = !selection.length;
    },
    handleHeaderClick(column, event) {
      console.log(column, event, 11111);
    },
    handleCellDblclick(row, column, cell, event){
      console.log(row, column, cell, event, 222222);
    },
    handleRowClick(row, column, event){
      console.log(row, column, event, 333333);
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getCycle(id).then((response) => {
        response.data.classes =
          response.data.classes && response.data.classes.split(",");
        this.form = response.data;
        this.open = true;
        this.title = "修改周期班";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.checkClassesList.length) {
            this.form.classes = this.checkClassesList
              .map((item) => item.classesName)
              .join(",");
          } else {
            this.$modal.msgError("请选择班次!");
            return;
          }
          if (this.form.id != null) {
            updateCycle(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addCycle(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除该条数据？')
        .then(function () {
          return delCycle(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "cycle/cycle/export",
        {
          ...this.queryParams,
        },
        `cycle_${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>
<style lang="scss" scoped>
.month-text {
  text-align: center;
  color: #999999;
  cursor: pointer;
  &.active {
    color: #000000;
    font-weight: bold;
  }
}
.option-block {
  margin: 16px 0;
  .option-line {
    display: flex;
    align-items: flex-start;
    margin-bottom: 16px;
    font-size: 14px;
    .line-label {
      color: #000000;
      font-weight: bold;
      margin-right: 10px;
    }
    .line-value {
      flex: 1;
    }
  }
}
</style>